package com.seeyoui.kensite.framework.oa.applyActivity.service;

import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.seeyoui.kensite.common.base.service.BaseService;
import com.seeyoui.kensite.common.exception.CRUDException;
import com.seeyoui.kensite.common.util.Collections3;
import com.seeyoui.kensite.common.util.StringUtils;
import com.seeyoui.kensite.framework.oa.applyActivity.domain.ApplyActivity;
import com.seeyoui.kensite.framework.oa.applyActivity.persistence.ApplyActivityMapper;
import com.seeyoui.kensite.framework.system.service.SysDepartmentService;
import com.seeyoui.kensite.framework.system.service.SysUserService;
@Service
public class BranchApplyActivityService extends BaseService  {
	
	@Autowired
	private ApplyActivityMapper applyActivityMapper;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysDepartmentService sysDepartMentService;
	
	/**
	 * 获取流程详细及工作流参数
	 * @param id
	 */
	@SuppressWarnings("unchecked")
	public ApplyActivity findApplyActivityById(String id) {
		ApplyActivity applyActivity = applyActivityMapper.findApplyActivityById(id);
		Map<String,Object> variables=null;
		HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(applyActivity.getBindId()).singleResult();
		if(historicProcessInstance!=null) {
			variables = Collections3.extractToMap(historyService.createHistoricVariableInstanceQuery().processInstanceId(historicProcessInstance.getId()).list(), "variableName", "value");
		} else {
			variables = runtimeService.getVariables(runtimeService.createProcessInstanceQuery().processInstanceId(applyActivity.getBindId()).active().singleResult().getId());
		}
		applyActivity.setVariables(variables);
		Task task = taskService.createTaskQuery().processInstanceId(applyActivity.getBindId()).active().singleResult();
		if(task!=null) {
			applyActivity.setTask(task);
			applyActivity.getAct().setTask(task);
		} else {
			HistoricTaskInstance histTask  = historyService.createHistoricTaskInstanceQuery().processInstanceId(applyActivity.getBindId()).orderByHistoricTaskInstanceEndTime().desc().list().get(0);
			applyActivity.getAct().setHistTask(histTask);
		}
		return applyActivity;
	}
	
	/**
	 * 启动流程
	 * @param leave
	 * @param variables
	 */
	public void start(ApplyActivity applyActivity, Map<String, Object> variables) {
		if("党员活动".equals(applyActivity.getType())){
			applyActivity.setApplySate("0");
			// 保存业务数据
			if (StringUtils.isBlank(applyActivity.getId())){
				applyActivity.preInsert();
				applyActivityMapper.saveApplyActivity(applyActivity);
			}else{
				applyActivity.preUpdate();
				applyActivityMapper.updateApplyActivity(applyActivity);
			}
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(applyActivity.getCurrentUser().getUserName());
			// 启动流程
			String businessKey = applyActivity.getId();
			variables.put("type", "branchApply");
			variables.put("busId", businessKey);
			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("branchApply", businessKey, variables);
			// 更新流程实例ID
			applyActivity.setBindId(processInstance.getId());
			applyActivityMapper.updateBindid(applyActivity);
			
		}else{
			applyActivity.setApplySate("1");
			applyActivity.setState("未开始");
			// 保存业务数据
			if (StringUtils.isBlank(applyActivity.getId())){
				applyActivity.preInsert();
				applyActivityMapper.saveApplyActivity(applyActivity);
			}else{
				applyActivity.preUpdate();
				applyActivityMapper.updateApplyActivity(applyActivity);
			}
		}
	}
	
	/**
	 * 数据新增或修改
	 * @param leave
	 * @throws CRUDException
	 */
	public void saveOrUpdate(ApplyActivity applyActivity) throws CRUDException{
		// 保存业务数据
		if (StringUtils.isBlank(applyActivity.getId())){
			applyActivity.preInsert();
			applyActivityMapper.saveApplyActivity(applyActivity);
		}else{
			applyActivity.preUpdate();
			applyActivityMapper.updateApplyActivity(applyActivity);
		}
	}

}
